package com.asdf.application.commands.dialogHandlers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JOptionPane;

import com.asdf.application.Constants;
import com.asdf.db.DataBase;
import com.asdf.db.DataBase.DataSource;
import com.asdf.db.operations.companyclub.GetCompanyClubOp;
import com.asdf.db.results.ResultStatus;
import com.asdf.db.results.companyclub.CompanyClubResult;
import com.asdf.entities.CompanyClub;
import com.asdf.external.INetserviceSimulator;
import com.asdf.external.IVSDT;
import com.asdf.external.stubs.VSDT;
import com.asdf.ui.CreditCardDetailsDialog;
import com.asdf.ui.SubscribeDialog;

/**
 * @author Artem Barger
 * 
 * Handler which capable to handle action of subscribing new user.
 *
 */
public class DialogHandlerSubscribeUser implements IDialogHandler
{
	private static final String	CANCEL_CMD	= "CANCEL";
	private static final String	OK_CMD		= "OK";
	private SubscribeDialog	dlg;

	/**
	 * @param dlg reference to attached dialog window
	 */
	public DialogHandlerSubscribeUser( SubscribeDialog dlg)
	{
		this.dlg = dlg;
	}

	/* (non-Javadoc)
	 * @see com.asdf.application.commands.dialogHandlers.IDialogHandler#handle(com.asdf.external.INetserviceSimulator)
	 */
	@SuppressWarnings({ "unchecked" })
	@Override
	public void handle( final INetserviceSimulator simulator)
	{
		final String firstName 		= dlg.getFirstName( );
		final String lastName 		= dlg.getLastName( );
		final String userNickName	= dlg.getUserNickName( );
		final String userId 		= dlg.getUserId( );
		final String address 		= dlg.getAddress( );
		final String email 			= dlg.getEmail( );
		
		final boolean getNewsLetters 		= dlg.sendHardCopyBill( );
		final String aviationCompanyName 	= dlg.getAviationCompanyName( );
		final boolean aviationClubMember 	= ( null != aviationCompanyName && aviationCompanyName.length( )>0);

		dlg.dispose( );
				
		GetCompanyClubOp locateClub = new GetCompanyClubOp( ( List<CompanyClub> ) DataBase.getInstance( ).getDataSource( DataSource.CompanyClubs));
		locateClub.setCompanyName( aviationCompanyName);
		CompanyClubResult result = ( CompanyClubResult ) DataBase.getInstance( ).Do( locateClub);
		
		CompanyClub company = null;
		
		if ( result.getStatus( ) == ResultStatus.OK)
		{
			company = result.getCompany( );
		}
		
		double discount = (company == null)? 0:company.getDiscount( );
		
		if ( discount == 1)
		{
			IVSDT vsdt = new VSDT();
			String initPwd = simulator.subscribe(
					vsdt.encrypt(userId), vsdt.encrypt(firstName), vsdt.encrypt(lastName),
					vsdt.encrypt(email), vsdt.encrypt(address), 
					aviationClubMember, vsdt.encrypt(aviationCompanyName), getNewsLetters, 
					vsdt.encrypt(userNickName));
			
			showSubscriptionResult( null, initPwd);
		}
		else
		{
			final CreditCardDetailsDialog creditCardDetailsDialog = new CreditCardDetailsDialog( );

			creditCardDetailsDialog.registerEventHandlerCancelCommand( CANCEL_CMD, 
					new ActionListener( )
			{

				@Override
				public void actionPerformed( ActionEvent arg0)
				{
					if ( arg0.getActionCommand( ).equalsIgnoreCase( CANCEL_CMD))
						creditCardDetailsDialog.dispose( );
				}

			});
			creditCardDetailsDialog.registerEventHandlerOkCommand( OK_CMD, 
					new ActionListener( )
			{

				@Override
				public void actionPerformed( ActionEvent arg0)
				{
					if ( arg0.getActionCommand( ).equalsIgnoreCase( OK_CMD))
					{
						String ccProvider = creditCardDetailsDialog
										.getCompanyName( );
						String cardNumber = creditCardDetailsDialog
										.getCardNumber( );
						String ccExpirationMonth = creditCardDetailsDialog
										.getExpirationMonth( );
						String ccExpirationYear = creditCardDetailsDialog
										.getExpirationYear( );
						String ccZIP = creditCardDetailsDialog.getZip( );

						String initPwd;
						try
						{
							IVSDT vsdt = new VSDT();
							initPwd = simulator.subscribe(
									vsdt.encrypt(userId), vsdt.encrypt(firstName), vsdt.encrypt(lastName),
									vsdt.encrypt(email), vsdt.encrypt(address), 
									aviationClubMember, vsdt.encrypt(aviationCompanyName), 
									getNewsLetters, vsdt.encrypt(userNickName), 
									vsdt.encrypt(cardNumber), vsdt.encrypt(ccProvider), 
									Integer.parseInt( ccExpirationMonth), 
									Integer.parseInt( ccExpirationYear), Integer.parseInt(ccZIP));
							
							showSubscriptionResult( creditCardDetailsDialog, initPwd);

						}
						catch ( NumberFormatException e )
						{
							JOptionPane.showMessageDialog( creditCardDetailsDialog, 
				  					   					   "Error in input fields, please try again!", 
				  					   					   Constants.ERROR_CAPTION_DLG, 
				  					   					   JOptionPane.ERROR_MESSAGE);

						}
						finally
						{
							creditCardDetailsDialog.dispose( );
						}
					}
				}

			});
			creditCardDetailsDialog.setVisible( true);
		}
	}
	
	/**
	 * Method which show to the user status message of his subscription.
	 * 
	 * @param dialog the owner dialog ( should be null if there is no such)
	 * @param initPwd the initial password to show.
	 */
	public void showSubscriptionResult(
			final CreditCardDetailsDialog dialog,
			String initPwd)
	{
		if ( null != initPwd) 
			JOptionPane.showMessageDialog( dialog, 
					"Your initial password is: " + initPwd + "\n Try to connect, in 5 min.", 
					"Initial password", JOptionPane.INFORMATION_MESSAGE);
		else
			JOptionPane.showMessageDialog( dialog, 
					"Error in subscribing", "Error", JOptionPane.ERROR_MESSAGE);

	}
}